<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\api\controller;

use app\common\model\Goods;
use app\common\model\GoodsComment as GoodsCommentModel;
use app\common\model\CommentLike;
use app\service\uploads\UploadService;
use Webman\Event\Event;

/**
 * 商品评论控制器
 */
class GoodsComment extends Base
{
    /**
     * 获取商品评论列表
     */
    public function lists()
    {
        $goods_id = request()->post('goods_id', 0);
        $limit    = request()->post('limit', 10);
        $order_by = request()->post('order_by', 'create_time'); // 排序方式

        if (empty($goods_id)) {
            return $this->error('参数错误');
        }

        $goods = Goods::where('status', 1)->find($goods_id);
        if (!$goods) {
            return $this->error(trans('goods_not_exists'));
        }

        // 构建排序规则
        $order_field = 'create_time';
        $order_type  = 'asc';

        if ($order_by == 'create_time') {
            $order_field = 'create_time';
            $order_type  = 'asc';
        } else if ($order_by == 'reply_time') {
            $order_field = 'create_time';
            $order_type  = 'desc';
        } else if ($order_by == 'likes') {
            $order_field = 'likes';
            $order_type  = 'desc';
        }
        // 使用 paginate 进行分页查询
        $comments = GoodsCommentModel::with(['user' => function ($query) {
            $query->field('id,username,avatar,nickname');
        },
            'replies' => function ($query) {
                $query->with(['user' => function ($q) {
                    $q->field('id,username,avatar,nickname');
                }
                ]);
            }
        ])
            ->where([
                'goods_id'  => $goods_id,
                'status'    => GoodsCommentModel::STATUS_APPROVED,
                'parent_id' => 0  // 只查询一级评论
            ])
            ->field('id,goods_id,user_id,content,parent_id,create_time,update_time,likes')
            ->order($order_field, $order_type)->paginate($limit)->each(function ($item) {
                if ($this->user_id) {
                    $item->is_liked = CommentLike::isLiked($this->user_id, $item['id']);
                } else {
                    $item->is_liked = false;
                }
            });

        return $this->success('获取成功', [
            'list'  => $comments->items(),
            'total' => $comments->total()
        ]);
    }

    /**
     * 提交评论
     */
    public function submit()
    {
        if (!$this->user_id) {
            return $this->error('请先登录');
        }
        // 检查是否有nickname
        if (empty($this->user->nickname)) {
            return $this->error('请先在个人中心设置一个闪亮的昵称吧~');
        }

        $goods_id  = $this->request->post('goods_id', 0);
        $content   = $this->request->post('content', '');
        $parent_id = $this->request->post('parent_id', 0);
        $images    = $this->request->post('images', []);
        $files     = $this->request->post('attachments', []);

        // 参数验证
        if (empty($goods_id)) {
            return $this->error('商品ID不能为空');
        }

        if (empty($content)) {
            return $this->error('评论内容不能为空');
        }

        if (mb_strlen($content) > 500) {
            return $this->error('评论内容不能超过500字');
        }

        // 检查违禁词 hook todo

        $goods = Goods::where('status', 1)->find($goods_id);
        if (!$goods) {
            return $this->error(trans('goods_not_exists'));
        }

        $comment_data = [
            'goods_id'  => $goods_id,
            'user_id'   => $this->user_id,
            'content'   => $content,
            'parent_id' => $parent_id,
            'status'    => GoodsCommentModel::STATUS_APPROVED, // 默认已审核，允许所有已登录用户评论
            'is_admin'  => 0,
            'likes'     => 0 // 初始点赞数为0
        ];

        // 更新商品评论计数
        $goods->setInc('comments_count');

        // 循环 图片或者附件标签 加到评论的后面
        foreach ($images as $image) {
            $comment_data['content'] .= '<img src="' . $image . '" alt="图片">';
        }
        foreach ($files as $file) {
            $comment_data['content'] .= '<a href="' . $file . '" target="_blank">' . $file . '</a>';
        }

        $comment = GoodsCommentModel::create($comment_data);

        Event::dispatch('goods.comment.submit', $comment);

        return $this->success('评论提交成功', $comment);
    }

    /**
     * 点赞评论
     */
    public function like()
    {
        if (!$this->user_id) {
            return $this->error('请先登录');
        }

        $comment_id = request()->post('comment_id', 0);
        if (empty($comment_id)) {
            return $this->error('评论ID不能为空');
        }

        $comment = GoodsCommentModel::where('id', $comment_id)->find();
        if (!$comment) {
            return $this->error('评论不存在');
        }
        if ($comment->user_id == $this->user_id) {
            return $this->error('不能给自己点赞');
        }

        // 检查用户是否已点赞该评论
        $is_liked = CommentLike::isLiked($this->user_id, $comment_id);

        // 如果已点赞，则取消点赞
        if ($is_liked) {
            // 删除点赞记录
            CommentLike::where([
                'user_id'    => $this->user_id,
                'comment_id' => $comment_id
            ])->delete();

            // 减少点赞数
            $comment->setDec('likes');

            return $this->success('取消点赞成功', [
                'is_liked' => false,
                'likes'    => $comment->likes
            ]);
        } else {
            // 添加点赞记录
            CommentLike::create([
                'user_id'    => $this->user_id,
                'comment_id' => $comment_id
            ]);

            // 增加点赞数
            $comment->setInc('likes');

            Event::dispatch('goods.comment.like', $comment);

            return $this->success('点赞成功', [
                'is_liked' => true,
                'likes'    => $comment->likes
            ]);
        }
    }

    // 批量上传图片
    public function uploadImage()
    {
        if (!$this->user_id) {
            return $this->error('请先登录');
        }

        $files = request()->file('file');
        // 如果是多文件上传 则循环上传
        if (is_array($files)) {
            foreach ($files as $file) {
                $res   = (new UploadService())->upload('user', $file, 'image', $this->user_id);
                $res[] = $res;
            }
        } else {
            $res = (new UploadService())->upload('user', $files, 'image', $this->user_id);
        }
        return $this->success('上传成功', $res);
    }

    // 批量上传附件
    public function uploadAttachment()
    {
        if (!$this->user_id) {
            return $this->error('请先登录');
        }

        $files = request()->file('file');
        // 如果是多文件上传 则循环上传
        if (is_array($files)) {
            foreach ($files as $file) {
                $res   = (new UploadService())->upload('user', $file, 'archive', $this->user_id);
                $res[] = $res;
            }
        } else {
            $res = (new UploadService())->upload('user', $files, 'archive', $this->user_id);
        }
        return $this->success('上传成功', $res);
    }
}